//
//  PriceQueryDetailViewController.m
//  WorkNest
//
//  Created by qbm360 on 15/7/27.
//  Copyright (c) 2015年 nest. All rights reserved.
//

#import "PriceQueryDetailViewController.h"
#import "ImageAddingView.h"
#import "PriceQueryViewController.h"
#import "PriceQueryChooseViewController.h"
#import "ReportPriceDetailsViewController.h"
#import "PriceQueryModel.h"
#import "DeliveryRecordViewController.h"
#import "BulkorderModel.h"

@interface PriceQueryDetailViewController () <UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (strong, nonatomic) NSArray *array;
@property (strong, nonatomic) NSArray *detailArray;
@property (weak, nonatomic) IBOutlet UIButton *statusButton;
@property (weak, nonatomic) IBOutlet UIButton *developButton;
@property (weak, nonatomic) IBOutlet UIButton *reInquiry;
@property (nonatomic, strong) PriceQueryModel *model;
@property (nonatomic, strong) QueryQuoteModel *queryQuoteModel;
@property (nonatomic, strong) ImageAddingView *imageAddingView;

@end

@implementation PriceQueryDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self titleView:self.ifPriceQuery ? @"询价单详情":@"制版打样详情"];
    if (self.ifPriceQuery) {
        self.array = @[@"单号",@"询价日期",@"定制产品名称",@"产品是否有样衣",@"面辅料",@"面辅料备注",@"商品吊牌",@"包装",@"预计每次订单件数",@"预计大货下单时间",@"打样前是否选主面料",@"产品链接",@"产品详细说明",@"",@"报价单"];
    } else {
        self.array = @[@"单号",@"下单日期",@"定制产品名称",@"产品是否有样衣",@"面辅料",@"面辅料备注",@"商品吊牌",@"包装",@"要求样衣交付时间",@"预计大货下单时间",@"打样前是否选主面料",@"产品链接",@"产品详细说明",@"",@"报价单"];
    }
    
    self.developButton.hidden = YES;
    self.reInquiry.hidden = !self.ifPriceQuery;
    [self requestData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if ([self.myTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.myTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.myTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.myTableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)statusRecord {
    DeliveryRecordViewController *view = [[DeliveryRecordViewController alloc] init];
    BulkorderModel *bulkorderModel = [[BulkorderModel alloc] init];
    bulkorderModel.orderId = self.ifPriceQuery?_model.inquireId:_model.needId;
    view.model = bulkorderModel;
    view.ifBulkorder = NO;
    [self.navigationController pushViewController:view animated:YES];
}

- (void)requestData {
    [ESHUDView showLoading];
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken, self.ifPriceQuery? @"inquireId":@"needId":self.needId};
    [RequestData developDetailParameters:[UIUtil toJsonString:dic] url:self.ifPriceQuery?@"/gckjapi/queryInquireDetail":@"/gckjapi/queryNeedDetail" withBlock:^(PriceQueryModel *model, QueryQuoteModel *queryQuoteModel, NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"请求失败":msg dismissBlock:nil];
            }
        } else {
            self.model = model;
            self.queryQuoteModel = queryQuoteModel;
            [self.myTableView reloadData];
            [ESHUDView dismiss];
        }
    }];
}

- (void)setModel:(PriceQueryModel *)model {
    _model = model;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"状态记录" style:UIBarButtonItemStyleBordered target:self action:@selector(statusRecord)];
    NSMutableArray *array = [NSMutableArray array];
    for (int i=0; i<self.model.imageList.count; i++) {
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[UIUtil containString:_model.imageList[i]]]]];
        [array addObject:image];
    }
    _imageAddingView = [[ImageAddingView alloc] initWithFrame:CGRectMake(0, 15, SCREEN_WIDTH, 100)];
    _imageAddingView.imageDatas = array;
    _imageAddingView.ifHiddenAddBtn = YES;
    
    if ([model.inquireOrderStatus isEqualToString:@"1106"]) {
        self.developButton.hidden = NO;
    }
    if ([model.status isEqualToString:@"1210"]) {
        self.reInquiry.hidden = NO;
        [self.statusButton setTitle:@"样衣确认" forState:UIControlStateNormal];
    }
    [self.statusButton setTitle:_model.statusNote forState:UIControlStateNormal];
    NSString *string = @"";
    if (self.ifPriceQuery) {
        string = _model.predictPerOrderNumber == nil ? @"" : _model.predictPerOrderNumber;
    } else {
        string = _model.splDeliveryTime == nil ? @"" : [_model.splDeliveryTime substringToIndex:10];
    }
    self.detailArray = @[self.ifPriceQuery ? _model.inquireId : _model.needId,
                         self.ifPriceQuery ?[_model.date substringToIndex:10]:[_model.orderTime substringToIndex:10],
                         self.ifPriceQuery ? _model.inquireProductName :_model.developProductName,
                         [_model.isProductSPL integerValue]?@"是":@"否",
                         [_model.accessory integerValue] == 10 ? @"包工包料":[_model.accessory integerValue] == 11 ? @"清加工" :[_model.accessory integerValue] == 12 ? @"我指定面辅料供应商" : @"其他",
                         _model.remark == nil ? @"":_model.remark,
                         [_model.mark integerValue] == 20 ?@"我提供":[_model.mark integerValue] == 21?@"不需要":@"委托采购",
                         [_model.pack integerValue] == 30 ?@"我提供":[_model.pack integerValue] == 31?@"不需要":@"委托采购",
                         string,
                         _model.predictBulkOrderTime == nil ? @"" : [_model.predictBulkOrderTime substringToIndex:10],
                         [_model.isChoiceMainfabric integerValue]?@"是":@"否",
                         _model.storeAddress == nil ? @"" : _model.storeAddress,
                         _model.productDetailRequire,
                         @"",@""];
}

#pragma mark - action methods
- (IBAction)statusButton:(id)sender {
}

- (IBAction)developButton:(id)sender {
    if (_ifPriceQuery) {
        [ESHUDView showLoading];
        NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken, @"inquireId":self.model.inquireId==nil?@"":self.model.inquireId};
        [RequestData inquireDevelopParameters:[UIUtil toJsonString:dic] withBlock:^(NSString *msg, NSError *error) {
            if (error) {
                if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                    [UIUtil tokenOverdue:self msg:msg];
                } else {
                    [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"请求失败":msg dismissBlock:nil];
                }        } else {
                    [[ESHUDView sharedInstance] showSuccessMessage:msg dismissBlock:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                }
        }];
    } else {
        [ESHUDView showLoading];
        NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken, @"orderId":self.model.needId==nil?@"":self.model.needId};
        [RequestData needConfirmParameters:[UIUtil toJsonString:dic] withBlock:^(NSString *msg, NSError *error) {
            if (error) {
                if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                    [UIUtil tokenOverdue:self msg:msg];
                } else {
                    [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"确认失败":msg dismissBlock:nil];
                }        } else {
                    [[ESHUDView sharedInstance] showSuccessMessage:msg dismissBlock:nil];
                }
        }];
    }
}

- (IBAction)priceQueryAgainButton:(id)sender {
    PriceQueryViewController *view = [[PriceQueryViewController alloc] init];
    NSArray *array = @[@[_detailArray[2],_detailArray[3],_detailArray[4],_detailArray[5]],@[_detailArray[6],_detailArray[7],@"",_detailArray[8],_detailArray[9],_detailArray[10]],@[_detailArray[11],_detailArray[12]]];
    view.detailArray = array;
    view.imageList = _imageAddingView.imageDatas;
    view.model = self.model;
    view.priceTitle = @"询价单";
    [self.navigationController pushViewController:view animated:YES];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    if (indexPath.row != self.array.count-2) {
        cell.textLabel.textColor = [UIUtil colorWithHexString:@"#5f5f5f"];
        cell.textLabel.text = [self.array objectAtIndex:indexPath.row];
        [cell.textLabel setFont:[UIFont systemFontOfSize:14]];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, 44)];
        label.textColor = [UIUtil colorWithHexString:@"#5f5f5f"];
        label.text = [self.detailArray objectAtIndex:indexPath.row];
        [label setFont:[UIFont systemFontOfSize:14]];
        [cell addSubview:label];
    } else {
        if (self.model.imageList.count>0) {
            [cell addSubview:_imageAddingView];
        } else {
            cell.hidden = YES;
        }
    }
    if (indexPath.row == self.array.count - 3 || indexPath.row == self.array.count - 1) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.myTableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == self.array.count - 3) {
        PriceQueryChooseViewController *view = [[PriceQueryChooseViewController alloc] init];
        view.choose = @"1";
        view.detailText = _model.productDetailRequire;
        [self.navigationController pushViewController:view animated:YES];
    } else if (indexPath.row == self.array.count - 1) {
        if (!self.queryQuoteModel.quoteId) {
            [[ESHUDView sharedInstance] showErrorMessage:@"该订单没有对应报价信息！" dismissBlock:nil];
            return;
        }
        ReportPriceDetailsViewController *view = [[ReportPriceDetailsViewController alloc] init];
        view.quoteId = self.queryQuoteModel.quoteId;
//        view.quoteId = self.ifPriceQuery?self.model.inquireId:self.model.needId;
        [self.navigationController pushViewController:view animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == self.array.count - 2 && self.model.imageList.count >0) {
        return 100;
    } else if (indexPath.row == self.array.count - 2 && !self.model.imageList.count >0) {
        return 0;
    }
    return 44;
}

@end
